// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();

/**
 * 
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const db = cloud.database();
  const _ = db.command;
  const $ = _.aggregate;
  const LIMIT = 100;

  var key = event.key;
  var results = await db.collection('post')
    .aggregate()
    .match({
      title: {
        $regex: '.*' + key,
        $options: 'i'
      }
    })
    .lookup({
      from: 'user',
      let: {
        authorOpenid: '$_openid'
      },
      pipeline: $.pipeline()
        .match(_.expr($.eq(['$_openid', '$$authorOpenid'])))
        .project({
          _id: 0,
          nickName: 1,
          avatarUrl: 1
        }).done(),
      as: 'authorInfo'
    })
    .replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$authorInfo', 0]), '$$ROOT'])
    })
    .project({
      authorInfo: 0,
      members: 0
    })
    .end();

  return {
    errCode: 0,
    data: results.list
  };
}